package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.UserCourseTimeStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.EmojiConverterUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.wechat.WechatProperties;
import com.ruoyi.system.domain.SpokenTeacher;
import com.ruoyi.system.domain.SpokenUser;
import com.ruoyi.system.domain.SpokenUserCourseTime;
import com.ruoyi.system.domain.model.MiniRegisterBody;
import com.ruoyi.system.mapper.SpokenUserCourseTimeMapper;
import com.ruoyi.system.mapper.SpokenUserMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SpokenUserServiceImpl implements ISpokenUserService {

    @Autowired
    SpokenUserMapper userMapper;

    @Autowired
    ISysUserService sysUserService;

    @Autowired
    ISpokenTeacherService teacherService;

    @Autowired
    WechatProperties wechatProperties;

    @Autowired
    ISpokenUserCourseTimeService userCourseTimeService;

    @Override
    public int insert(SpokenUser user) {
        return userMapper.insert(user);
    }

    @Override
    public SpokenUser selectById(Long userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public List<SpokenUser> selectList(SpokenUser user) {
        return userMapper.selectList(user);
    }

    @Override
    @Transactional
    public int update(SpokenUser user) {
        // 修改主表信息
        user.getSysUser().setUserId(user.getUserId());
        if(user.getEnglishName() != null || user.getAge() != null){
            userMapper.update(user);
        }
        return sysUserService.updateUserProfile(user.getSysUser());
    }

    /**
     * 微信注册
     * @param
     */
    @Override
    @Transactional
    public SpokenUser wechatRegister(MiniRegisterBody miniRegisterBody) {
        // 授权获取openId
        String openIdFullUrl = String.format(wechatProperties.getOpenIdUrl(), wechatProperties.getAppId(), wechatProperties.getAppSecret(), miniRegisterBody.getCode());
        String result = HttpUtils.sendGet(openIdFullUrl);
        String openId = JSONObject.parseObject(result).getString("openid").toString();
        // 用户主表
        SysUser sysUser = new SysUser();
        sysUser.setUserName(openId);
        boolean unique = sysUserService.checkUserNameUnique(sysUser);
        if(!unique){
            throw new ServiceException("当前用户已注册");
        }
        sysUser.setPassword(SecurityUtils.encryptPassword(openId));
        sysUser.setNickName(EmojiConverterUtil.emojiConverter.toHtml(miniRegisterBody.getNickName()));
        sysUser.setAvatar(miniRegisterBody.getAvatar());
        sysUser.setCreateTime(new Date());
        sysUser.setRoleId(100l);   // 角色：移动端用户
        sysUser.setUserType("01");  // 用户类型：小程序用户
        sysUser.setStatus("0");
        sysUser.setDelFlag("0");
        sysUserService.insertUser(sysUser);

        // 用户子表
        SpokenUser spokenUser = new SpokenUser();
        spokenUser.setUserId(sysUser.getUserId());
        spokenUser.setOpenId(openId);
        spokenUser.setCreateTime(sysUser.getCreateTime());
        spokenUser.setSysUser(sysUser);
        this.insert(spokenUser);

        return spokenUser;
    }


    /**
     * 小程序登录
     * @param code
     * @return
     */
    @Override
    public SpokenUser wechatLogin(String code) {
        // 授权获取openId
        String openIdFullUrl = String.format(wechatProperties.getOpenIdUrl(), wechatProperties.getAppId(), wechatProperties.getAppSecret(), code);
        String result = HttpUtils.sendGet(openIdFullUrl);
        String openId = JSONObject.parseObject(result).getString("openid").toString();

        // 根据openid查询用户
        return userMapper.selectByOpenid(openId);
    }

    /**
     * 获取微信手机号
     * @param code
     * @return
     */
    @Override
    public String getWechatPhoneNumber(String code) {
        String fullPhoneNumberUrl = String.format(wechatProperties.getPhoneNumberUrl(), wechatProperties.getAccessToken());
        System.out.println("fullPhoneNumberUrl:" + fullPhoneNumberUrl);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        String resultStr = HttpUtils.sendPost(fullPhoneNumberUrl, jsonObject.toJSONString());
        JSONObject result = JSONObject.parseObject(resultStr);
        Map phoneInfo = (Map)result.get("phone_info");

        return (String)phoneInfo.get("phoneNumber");
    }

    /**
     * 根据用户ID查询用户选择的日期
     * @return
     */
    @Override
    public List<SpokenUserCourseTime> selectUserCourseTimeDate() {
        Long userId = SecurityUtils.getUserId();
        List<SpokenUserCourseTime> spokenUserCourseTimes = userCourseTimeService.selectUserCourseTimeByUserId(userId);
        return spokenUserCourseTimes;
    }

    @Override
    public List<Map> selectCourseTimeInfoByDate(String chooseDate) {
        List<Map> result = new ArrayList<>();
        Long userId = SecurityUtils.getUserId();
        List<SpokenUserCourseTime> spokenUserCourseTimes = userCourseTimeService.selectTeacherIdByDate(chooseDate, userId);
        for (SpokenUserCourseTime spokenUserCourseTime : spokenUserCourseTimes) {
            // 查询课时信息：条件为教师、日期、学生id
            spokenUserCourseTime.setUserId(userId);
            spokenUserCourseTime.setChooseDate(LocalDate.parse(chooseDate));
            // 查询课时状态为：正常、消课、请假
            List statusList = new ArrayList();
            statusList.add(UserCourseTimeStatus.NORMAL.getCode());
            statusList.add(UserCourseTimeStatus.CANCEL_LESSON.getCode());
            statusList.add(UserCourseTimeStatus.LEAVE.getCode());
            List<SpokenUserCourseTime> select =
                userCourseTimeService.select(spokenUserCourseTime).stream().filter(item -> statusList.contains(item.getStatus())).collect(Collectors.toList());
            // 今日没有该教师信息
            if(select.size() < 1){
                continue;
            }
            // 查询教师信息
            SpokenTeacher spokenTeacher = teacherService.selectById(spokenUserCourseTime.getTeacherId());
            // 查询购买当前教师的课节数（只查询状态为：正常、消课）
            Integer totalLessonNum = userCourseTimeService.selectLessonNumByTeacherId(userId, spokenUserCourseTime.getTeacherId());
            // 查询已消课节数
            Integer cancelLessonNum = userCourseTimeService.selectCancelLessonNumByTeacherId(userId, spokenUserCourseTime.getTeacherId());
            Map map = new HashMap();
            map.put("teacherInfo", spokenTeacher);
            map.put("courseTimes", select);
            map.put("totalLessonNum", totalLessonNum);
            map.put("cancelLessonNum", cancelLessonNum);
            result.add(map);
        }
        return result;
    }

    @Override
    public Integer selectUserCount(String startDate, String endDate) {
        return userMapper.selectUserCount(startDate, endDate);
    }
}
